package com.raychi.demo.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.raychi.demo.entity.Category;
import com.raychi.demo.service.CategoryService;
import com.raychi.demo.util.CategoryUtil;
import com.raychi.demo.util.JdbcUtil;

public class CategoryAction{
	private List<Category> list;
	private Category category;
	private CategoryService categoryService;
	
	public String list(){
		list = categoryService.getCategorys();
		return "list";
	}
	
	public String input(){
		return "input";
	}
	
	public String save(){
		categoryService.save(category);
		return list();
	}
	
	public String edit(){
		category = getCategoryByID(category.getId());
		return "edit";
	}
	
	public String update(){
		categoryService.update(category);
		return list();
	}
	
	public String delete(){
		categoryService.delete(category);
		return list();
	}
	
	public Category getCategoryByID(int id){
		Category category = null;
		Connection conn = null;
		try{
			conn = JdbcUtil.getConnection();
			Statement st = conn.createStatement();
			String sql = "select * from Category where id=" + id;
			ResultSet rs = st.executeQuery(sql);
			while(rs.next()){
				category = CategoryUtil.creatCategory(rs);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return category;
	}
	
	public List<Category> getList() {
		return list;
	}
	public void setList(List<Category> list) {
		this.list = list;
	}
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}
}
